App = {
    web3Provider: null,
    contracts: {},
    account: '0x0',
    flag: 1,

    init: function () {
        return App.initWeb3();
    },

    initWeb3: function () {
        if (typeof window.ethereum !== 'undefined') {
            // If a web3 instance is already provided by Meta Mask.
            App.web3Provider = window.ethereum;
            web3 = new Web3(window.ethereum);
        } else {
            // Specify default instance if no web3 instance provided
            App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
            web3 = new Web3(App.web3Provider);
        };
        return App.initContract();
    },

    initContract: function () {
        $.getJSON("../Info.json", function (infomation) {
            // Instantiate a new truffle contract from the artifact
            App.contracts.Info = TruffleContract(infomation);
            // Connect provider to interact with contract
            App.contracts.Info.setProvider(App.web3Provider);
            return App.render();
        });
    },

    render: function () {

        // Load account data
        web3.eth.getCoinbase(function (err, account) {
            if (err === null) {
                App.account = account;
                App.EventDisplay();
            }
        });
    },

    /*活动数量*/
    eventCount: function () {
        App.contracts.Info.deployed().then(function (instance) {
            InfoInstance = instance;
            console.log(InfoInstance.eventcount());
            return InfoInstance.eventcount();
        }).then(function (eventcount) {
            //控制台输出
            console.log(eventcount);
        })
    },

    EventRelease: function () {
        var eventname = $("#eventname").val();
        console.log(eventname);
        var starttime = $("#starttime").val();
        console.log(starttime);
        var overtime = $("#overtime").val();
        console.log(overtime);
        App.contracts.Info.deployed().then(async function (instance) {
          var allsrc = "";
            for (var i = 0; i < imgArr.length; i++) {
                console.log(imgArr[i]);
                allsrc += imgArr[i] + "...";
            }
          instance.showTime({from: App.account, gas: 300000000});
          var time = await instance.timenow();
          EventInstance = instance;
          EventInstance.addEvent(eventname, starttime, overtime, time, imgArr.length, allsrc, App.account, { from: App.account, gas: '1000000000' });
            console.log("EventRelease Successfully!");
            alert("EventRelease Successfully!");
            location.reload(true);
        }).catch(function (error) {
            console.warn(error);
        });
    },

    EventDisplay: function () {

        //载入活动信息
        App.contracts.Info.deployed().then(function (instance){
            eventInstance = instance;
            return eventInstance.eventcount();
        }).then(function (eventcount) {
            console.log(eventcount);
            for (var i = 1; i <= eventcount; i++) {

                eventInstance.events(i).then(function (ent) {
                    var entId = ent[0];
                    console.log(entId);
                    var eventname = ent[1];
                    var starttime = ent[3];
                    var overtime = ent[4];
                    var submitTime = ent[5];
                    var imgcnt = ent[6];
                    var imgsrc = ent[7];
                    var img = imgsrc.split('...');
                    var list = document.querySelector("#list");//获取父结点
                    //创建一个活动标签
                    var eventli = document.createElement("li");
                    eventli.className = "info";
                    eventli.innerHTML = `
                        <span class="username">${UserHome.userName}'s plan<p class="star">&#9733;</p></span>
                        <p class="planname">${eventname}</p>
                        <p class="time" style="width=500px;">startime:${starttime}<br><br>endtime:${overtime}<br><br>releasetime:${submitTime}</p>
                    `;
                    for (var j = 0; j < img.length - 1; j++) {
                        eventli.innerHTML += " <div style='float: left;width: auto;height: 200px; margin-left: 10px;position: relative;margin-top: 20px;'> " +
                            "<img  style='width:auto; height: 200px' src=" + img[j] + ">" +
                            "</div>";
                        console.log(img[j]);
                    }
                    list.insertBefore(eventli, list[0]);
                    var star = eventli.querySelector(".star");
                    eventInstance.tpi_events_flag(UserHome.UserId, entId.c[0]).then(function(flag){
                        if(flag) star.style.color = "rgb(255, 203, 71)";
                    })
                    star.addEventListener("click", async function () {
                      eventInstance.tpi_events_flag(UserHome.UserId, entId.c[0]).then(function(flag){
                          if(!flag) star.style.color = "rgb(255, 203, 71)";
                          else star.style.color = "#ccc";
                      })
                        App.contracts.Info.deployed().then(function (instance) {
                            InfoInstance = instance;
                            console.log(entId.c[0]);
                            /*InfoInstance.addEvent(eventname, starttime, overtime);*/
                            InfoInstance.participate(UserHome.UserId, entId.c[0], { from: App.account, gas: '1000000000' });
                            console.log("participate successfully!")
                        })
                    })
                })
            }
        })
    },

};

$(function () {
    $(window).load(function () {
        App.init();
    });
});
